$(function() {

    var ROOT_URL ="/{{Request::segment(1)}}";
    var MODULE_URL = "/{{Request::segment(1)}}/{{Request::segment(2)}}";
    var MSG_LOAD_USERINFO_ERROR = "{{Lang::get('probackend::global.message_load_userinfo_error')}}";
    var MSG_LOAD_CREATE_FORM_ERROR = "{{Lang::get('probackend::global.message_load_create_form_error')}}";
    var MSG_LOAD_DETAIL_ERROR = "{{Lang::get('probackend::global.message_load_detail_error')}}";
    var MSG_LOAD_EDIT_FORM_ERROR = "{{Lang::get('probackend::global.message_load_edit_form_error')}}";
    var MSG_SUBMIT_CREATE_FORM_ERROR = "{{Lang::get('probackend::global.message_submit_create_form_error')}}";
    var MSG_SUBMIT_DELETE_RECORD_ERROR = "{{Lang::get('probackend::global.message_submit_detele_record_error')}}";
    var MSG_SUBMIT_UPDATE_FORM_ERROR = "{{Lang::get('probackend::global.message_submit_update_form_error')}}";



    /*===========================================================================
     *=========================================================================== 
     *       Global Helper Function
     *=========================================================================== 
     *=========================================================================== 
     */
    function errorMsg(code) {
        var statusErrorMap = {
            '400': "Server understood the request but request content was invalid.",
            '401': "Unauthorised access.",
            '403': "Forbidden resouce can't be accessed",
            '500': "Internal Server Error.",
            '503': "Service Unavailable"
        };
        return statusErrorMap[code];
    }

    function createDetailTd() {
        var nDetailTd = document.createElement('td');
        nDetailTd.className = "text-center table-actions";
        nDetailTd.innerHTML = '<i class="detail-toggle icon-plus-circle" style="color:green"><i>';
        return nDetailTd;
    }

    function createEditTh() {
        var nEditTh = document.createElement('th');
        nEditTh.className = "text-center table-actions";
        nEditTh.innerHTML = "Edit";
        return nEditTh;
    }

    function createDeleteTh() {
        var nDeleteTh = document.createElement('th');
        nDeleteTh.className = "text-center table-actions";
        nDeleteTh.innerHTML = "Delete";
        return nDeleteTh;
    }

    function createEditTd(dataId) {
        var nEditTd = document.createElement('td');
        nEditTd.className = "table-actions";
        var buttonEdit = document.createElement('button');
        buttonEdit.className = "btn btn-info btn-sm btn-icon crub-table-edit";
        buttonEdit.setAttribute("data-toggle", "modal");
        buttonEdit.setAttribute("data-target", "#crub-edit-model-dialog");
        buttonEdit.setAttribute("data-id", dataId);
        buttonEdit.innerHTML = '<i class="icon-pencil3"></i>';
        nEditTd.appendChild(buttonEdit);
        return nEditTd;
    }

    function createDeleteTd(dataId) {
        var nDeleteTd = document.createElement('td');
        nDeleteTd.className = "table-actions";
        var buttonDelete = document.createElement('button');
        buttonDelete.className = "btn btn-danger btn-sm btn-icon crub-table-delete";
        buttonDelete.setAttribute("data-id", dataId);
        buttonDelete.innerHTML = '<i class="icon-remove3"></i>';
        nDeleteTd.appendChild(buttonDelete);
        return nDeleteTd;
    }

    function closeDetails(dataTable, nTr) {
        $(this).toggleClass("icon-minus-circle");
        $(this).toggleClass("icon-plus-circle");
        $(this).css("color", "green");
        dataTable.fnClose(nTr);
    }

    function openDetail(dataTable, nTr, dataId) {
        $(this).toggleClass("icon-minus-circle");
        $(this).toggleClass("icon-plus-circle");
        $(this).css("color", "green");
        dataTable.fnOpen(nTr, '<div id="id-' + dataId + '"><div class="center">Loading ..</div></div>', 'details');
        $("#crub-datatable tbody tr td.details").attr("colspan", 10000);
    }



    /*===========================================================================
     *=========================================================================== 
     *       Global Process
     *=========================================================================== 
     *=========================================================================== 
     */


    /**
     * =========================================================================
     *      Load user info
     * =========================================================================     
     */
    $.ajax({
        url: ROOT_URL + "/userinfo",
        error: function(xhr) {
            $('#userinfo').remove();
            $.jGrowl(MSG_LOAD_USERINFO_ERROR + "</BR>" + xhr.status + " - " + errorMsg(xhr.status), {
                theme: 'growl-error'
            });             
        },
        success: function(data) {
            $('#userinfo').html(data);
        }
    });


    /**
     * =========================================================================
     * Process dropdown menu
     * =========================================================================     
     */

    $('.dropdown, .btn-group').on('show.bs.dropdown', function() {
        $(this).find('.dropdown-menu').first().stop(true, true).fadeIn(100);
    });
    $('.dropdown, .btn-group').on('hide.bs.dropdown', function() {
        $(this).find('.dropdown-menu').first().stop(true, true).fadeOut(100);
    });
    //===== Prevent dropdown from closing on click =====//
    $('.popup').click(function(e) {
        e.stopPropagation();
    });

    /**
     * =========================================================================
     * Layout options
     * =========================================================================     
     */
    $('.sidebar-wide li:not(.disabled) .expand, .sidebar-narrow .navigation > li ul .expand').collapsible({
        defaultOpen: 'second-level,third-level',
        cssOpen: 'level-opened',
        cssClose: 'level-closed',
        speed: 150
    });
    $('.sidebar-toggle').click(function() {
        $('.page-container').toggleClass('sidebar-hidden');
    });
    $('.navigation li.disabled a, .navbar-nav > .disabled > a').click(function(e) {
        e.preventDefault();
    });
    $(".styled, .multiselect-container input").uniform({ radioClass: 'choice', selectAutoWidth: false });


    @if ($needCrub)
        /*===========================================================================
        *=========================================================================== 
        *       Process for group modules
        *=========================================================================== 
        *=========================================================================== 
        */
        
        
        
        
        /**
         * =========================================================================
         * Adding details columm
         * =========================================================================     
         */
        $('#crub-datatable').on("draw.dt", function() {
            var emptyView = $(".dataTables_empty");

            if (emptyView.length > 0) {
                $(emptyView).attr("colspan", 1000);
                $(emptyView).css("text-align", "center");
            } else {
                $('#crub-datatable .table-actions').remove();
                var colummCount = $('#crub-datatable thead tr th').size();

                // ===== Add details ====
                $('#crub-datatable thead tr').each(function() {
                    var detailTr = document.createElement('th');
                    detailTr.className = "table-actions";
                    this.insertBefore(detailTr.cloneNode(true), this.childNodes[0]);
                });

                $('#crub-datatable tbody tr').each(function() {
                    this.insertBefore(createDetailTd().cloneNode(true), this.childNodes[0]);
                });

                // ===== Add tools ====
                $('#crub-datatable thead tr').each(function() {
                    this.insertBefore(createEditTh().cloneNode(true), this.childNodes[colummCount + 1]);
                    this.insertBefore(createDeleteTh().cloneNode(true), this.childNodes[colummCount + 1]);
                });
                $('#crub-datatable tbody tr').each(function() {
                    var dataId = oTable.fnGetData(this)[0];
                    this.insertBefore(createEditTd(dataId).cloneNode(true), this.childNodes[colummCount + 1]);
                    this.insertBefore(createDeleteTd(dataId).cloneNode(true), this.childNodes[colummCount + 1]);
                });
            }
        });




        /**
         * =========================================================================
         * Adding event listener when detail columm 
         * =========================================================================     
         */
        $(document).on('click', '#crub-datatable .detail-toggle', function() {
            var nTr = $(this).parents('tr')[0];

            if (oTable.fnIsOpen(nTr)) {
                // details already open. close it now
                closeDetails(oTable, nTr);
            } else {
                // open details
                var dataId = oTable.fnGetData(nTr)[0];
                openDetail(oTable, nTr, dataId);

                // load detail content
                $.ajax({
                    url: MODULE_URL +"/" + dataId,
                    error: function(xhr) {
                        $.jGrowl(MSG_LOAD_DETAIL_ERROR + "</BR>" + xhr.status + " - " + errorMsg(xhr.status), {
                            theme: 'growl-error'
                        });
                        closeDetails(oTable, nTr);
                    },
                    success: function(data) {
                        $('#id-' + dataId).html(data);
                    }
                });
            }
        });


        /**
         * =========================================================================
         * Load create form data
         * =========================================================================     
         */
        $.ajax({
            url: MODULE_URL +"/"+ "create",
            error: function(xhr) {
                $.jGrowl(MSG_LOAD_CREATE_FORM_ERROR + "</BR>" + xhr.status + " - " + errorMsg(xhr.status), {
                    theme: 'growl-error'
                });
            },
            success: function(data) {
                $('#crub-create-model-dialog .modal-body').html(data);
            }
        });


        /**
         * =========================================================================
         * Process load edit form content
         * =========================================================================     
         */
        $(document).on('click', "#crub-datatable button.crub-table-edit", function() {
            var id = $(this).attr("data-id");
            $.ajax({
                url: MODULE_URL+"/" + id + "/edit",
                type: 'GET',
                error: function(xhr) {
                    $.jGrowl(MSG_LOAD_EDIT_FORM_ERROR + "</BR>" + xhr.status + " - " + errorMsg(xhr.status), {
                        theme: 'growl-error'
                    });
                },
                success: function(data) {
                    $("#crub-edit-model-dialog .modal-body").html(data);
                }
            });
        });



        /**
         * =========================================================================
         * Process create model form submit
         * =========================================================================     
         */
        $("#crub-create-model-form").ajaxForm({
            beforeSubmit: function() {
                $("#crub-create-model-form").find(".spin").parent().show();
            },
            error: function(xhr) {
                $("#crub-create-model-form").find(".spin").parent().hide();
                $.jGrowl(MSG_SUBMIT_CREATE_FORM_ERROR + "</BR>" + xhr.status + " - " + errorMsg(xhr.status), {
                    theme: 'growl-error'
                });
            },
            success: function(data) {
                $("#crub-create-model-form").find(".spin").parent().hide();
                var response = JSON.parse(data);
                $.jGrowl(response.messages.join("</BR>"), {
                    header: response.title,
                    theme: response.success === 0 ? 'growl-error' : 'growl-success'
                });
                if (response.success === 1) {
                    oTable.fnDraw();
                    $("#crub-create-model-form").reset();
                }
            }
        });


        /**
         * =========================================================================
         * Process delete model
         * =========================================================================     
         */
        $(document).on('click', "#crub-datatable button.crub-table-delete", function() {
            var id = $(this).attr("data-id");
            if (confirm(DELETE_MESSAGE)) {
                $.ajax({
                    url: MODULE_URL +"/" + id,
                    type: 'DELETE',
                    error: function(xhr) {
                        $.jGrowl(MSG_SUBMIT_DELETE_RECORD_ERROR + "</BR>" + xhr.status + " - " + errorMsg(xhr.status), {
                            theme: 'growl-error'
                        });
                    },
                    success: function(data) {
                        var response = JSON.parse(data);
                        $.jGrowl(response.messages.join("</BR>"), {
                            header: response.title,
                            theme: response.success === 0 ? 'growl-error' : 'growl-success'
                        });
                        if (response.success === 1) {
                            oTable.fnDraw();
                        }
                    }
                });
            } else {
                return;
            }
        });


        /**
         * =========================================================================
         * Process edit form submit
         * =========================================================================     
         */
        $('#crub-edit-model-form').ajaxForm({
            error: function(xhr) {
                $.jGrowl(MSG_SUBMIT_UPDATE_FORM_ERROR + "</BR>" + xhr.status + " - " + errorMsg(xhr.status), {
                    theme: 'growl-error'
                });
            },
            success: function(data) {
                var response = JSON.parse(data);
                $.jGrowl(response.messages.join("</BR>"), {
                    header: response.title,
                    theme: response.success === 0 ? 'growl-error' : 'growl-success'
                });
                if (response.success === 1) {
                    oTable.fnDraw();
                    $('#crub-edit-model-dialog').modal('toggle');
                }
            }
        });


    @endif

});




